package com.love_weinuo.ui.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.lzy.okgo.callback.StringCallback;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.uikit.business.chat.group.model.GroupChatInfo;
import com.tencent.qcloud.uikit.business.chat.group.model.GroupChatManager;
import com.tencent.qcloud.uikit.business.chat.group.model.GroupMemberInfo;
import com.tencent.qcloud.uikit.business.chat.model.MessageInfo;
import com.tencent.qcloud.uikit.business.session.model.SessionInfo;
import com.tencent.qcloud.uikit.common.IUIKitCallBack;
import com.tencent.qcloud.uikit.operation.message.UIKitRequest;
import com.tencent.qcloud.uikit.operation.message.UIKitRequestDispatcher;
import com.love_weinuo.R;
import com.love_weinuo.bean.CreatePindanCallBackBean;
import com.love_weinuo.bean.LandListCallBackBean;
import com.love_weinuo.databinding.ActivitySelectPindanLandBinding;
import com.love_weinuo.ui.BaseActivity;
import com.love_weinuo.ui.adapter.OnItemClickListener;
import com.love_weinuo.ui.adapter.SelectPindanLandAdapter;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.ToastUtil;
import com.love_weinuo.util.dialog.InCommonDialog;
import com.love_weinuo.util.dialog.PayDialog;
import com.love_weinuo.util.dialog.SelectDrugDialog;
import com.love_weinuo.util.listener.OnBHClickListener;
import com.love_weinuo.util.listener.OnDrugSelectListener;
import com.love_weinuo.util.listener.OnLonglyListener;
import com.love_weinuo.util.listener.OnPindanPointListener;
import com.love_weinuo.util.timeutil.TimeUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.love_weinuo.bean.Constants.REQUEST_CODE_USER_SEARCH;

/**
 * Created by SensYang on 2019/03/01 17:43
 */

public class SelectPindanLandActivity extends BaseActivity {

    ActivitySelectPindanLandBinding binding;
    SelectPindanLandAdapter adapter;
    private List<LandListCallBackBean.ResultEntity.ResEntity> strs = new ArrayList<>();
    List<Integer> drugIds = new ArrayList<>();
    private ArrayList<GroupMemberInfo> mMembers = new ArrayList<>();
    String drupName, inviteCode = "", landId;
    String landArea, landName, titleName, allSize, startTime, stopTime, pinDanId, groupId, proderNumID;
    int porderNum, porderId;
    String userId = (String) SpUtils.get("module_user_id", "");
    List<String> landIds = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_select_pindan_land);
        binding.setActivity(this);
        initView();
    }

    private void initView() {
        add(this);
        titleName = getIntent().getStringExtra("module_land_title");
        allSize = getIntent().getStringExtra("module_land_size");
        startTime = getIntent().getStringExtra("module_land_start_time");
        stopTime = getIntent().getStringExtra("module_land_stop_time");
        porderNum = getIntent().getIntExtra("module_porder_num", 0);
        porderId = getIntent().getIntExtra("module_porder_id", 0);
        groupId = getIntent().getStringExtra("module_group_id");
        inviteCode = getIntent().getStringExtra("module_invite_code");
        setBack();
        setTitleText("选择要拼的地块");
        setRightText("完成");
        if (strs.size() == 0) {
            binding.recycler.setVisibility(View.GONE);
            binding.ilModuleNothing.setVisibility(View.VISIBLE);
        }
        adapter = new SelectPindanLandAdapter(this, strs);
        binding.recycler.setLayoutManager(new LinearLayoutManager(this));
        binding.recycler.setAdapter(adapter);
        adapter.setOnItemClickLitener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                LogUtil.e("点击去查看土地对应位置");
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        //药品选择点击监听
        adapter.setOnPindanPointListener(new OnPindanPointListener() {
            public void setOnPindanPointListener(final int position) {
                SelectDrugDialog dialog = new SelectDrugDialog(SelectPindanLandActivity.this, new OnDrugSelectListener() {
                    @Override
                    public void setOnDrugSelectListener(int drugId, String drugName) {
                        drugIds.add(drugId);
                        drupName = drugName;
                        strs.get(position).setDrugname(drugName);
                        strs.get(position).setDrugid(drugId);
                        adapter.notifyItemChanged(position);
                    }
                });
                dialog.show();
            }
        });

        //删除点击监听
        adapter.setOnLonglyListener(new OnLonglyListener() {
            @Override
            public void onLonelyListener(final int pos) {
                InCommonDialog dialog = new InCommonDialog(SelectPindanLandActivity.this);
                dialog.setTitleText("确定删除" + strs.get(pos).getName() + "?");
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        strs.remove(pos);
                        adapter.notifyDataSetChanged();
                        if (0 == strs.size()) {
                            binding.recycler.setVisibility(View.GONE);
                            binding.ilModuleNothing.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onCloseClick() {

                    }
                });
            }
        });

        binding.tvModuleAddLand.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rightText:
                if (landIds.size() == 0) {
                    showInCommonDialog("请选择拼单土地");
                    return;
                }

                String landIdStr = "";
                for (String ger : landIds) {
                    landIdStr = landIdStr + "," + ger;
                }

                if (landIdStr.length() == 1) {
                    showInCommonDialog("请选择拼单土地");
                    return;
                }

                if (TextUtils.isEmpty(userId)) {
                    ToastUtil.showToast("自动登录到期，请重新登录");
                    startActivity(new Intent(SelectPindanLandActivity.this, LoginActivity.class));
                    finish();
                }
                LogUtil.e("土地ID==>" + landIdStr);
                createPindanOrder(landIdStr.substring(1, landIdStr.length()));
                break;
            case R.id.tvModuleAddLand:
                startActivityForResult(new Intent(SelectPindanLandActivity.this, MyLandActivity.class), REQUEST_CODE_USER_SEARCH);
                break;
            default:
        }
    }

    public void createPindanOrder(String landIds) {
        String drupNames = "";
        for (int i = 0; i < strs.size(); i++) {
            if (0 == strs.get(i).getDrugid()) {
                showInCommonDialog("请选择" + strs.get(i).getName() + "的喷洒药物");
                return;
            }
            drupNames += "," + strs.get(i).getDrugid();
        }

        HTTPAPI.getInstance().sendPindan(titleName, userId, landIds, startTime, stopTime,
                drupNames.substring(1, drupNames.length()), allSize,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.e("发布拼单成功" + s);
                        CreatePindanCallBackBean bean = GsonUtil.GsonToBean(s, CreatePindanCallBackBean.class);
                        SpUtils.put("module_pindan_id", bean.getResult().getPorderid());
                        pinDanId = bean.getResult().getPorderid();
                        proderNumID = bean.getResult().getPordernumid();
                        showPayDialog();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        LogUtil.e("创建拼单失败" + e.getMessage());
                        showInCommonDialog("创建拼单失败,请重试");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_USER_SEARCH:
                    landArea = data.getStringExtra("module_land_area");
                    landName = data.getStringExtra("module_land_name");
                    landId = data.getStringExtra("module_land_id");
                    LogUtil.e("接收到选择地块 name-->" + landName + "  ID-->" + landId + "  area-->"+ landArea);
                    strs.add(new LandListCallBackBean.ResultEntity.ResEntity(landArea, 0,
                            0, landName, 0, "", "", "", 0));
                    if (strs.size() != 0) {
                        binding.ilModuleNothing.setVisibility(View.GONE);
                        binding.recycler.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                    landIds.add(landId);
                    break;
                default:
                    LogUtil.e("requestCode==>" + requestCode);
            }
        } else {
            LogUtil.e("resultCode==>" + resultCode);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void showPayDialog() {
        PayDialog dialog = new PayDialog(SelectPindanLandActivity.this);
        dialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onConfirmClick() {
                createOrder();
            }

            @Override
            public void onCloseClick() {
                createOrder();
            }
        });
        dialog.show();
    }


    public void createOrder() {
        HTTPAPI.getInstance().createOrder(userId, proderNumID,"0", new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("创建订单成功" + s);
                //                selectTypeMethod(groupId);
                updateGroupID();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("创建订单失败" + e.getMessage());
            }
        });
    }

    //    public void selectTypeMethod(final String groupId) {
    //        if (0 == porderNum && 0 == porderId) {
    //            updateGroupID();
    //        } else {
    //            joinGroup(groupId);
    //        }
    //    }

    //    public void joinGroup(final String groupId) {
    //        LogUtil.e("groupID-->" + groupId);
    //        TIMGroupManager.getInstance().applyJoinGroup(groupId,
    //                TIMManager.getInstance().getLoginUser(), new TIMCallBack() {
    //                    @Override
    //                    public void onError(final int code, final String desc) {
    //                        com.tencent.qcloud.uikit.common.component.video.util.LogUtil.e("加入群组失败" + code + "  " + desc);
    //                        switch (code) {
    //                            case 10013:
    //                                LogUtil.e("已经是群员，直接聊天");
    //                                ChatActivity.startGroupChat(SelectPindanLandActivity.this, groupId);
    //                                finish();
    //                                break;
    //                            default:
    //                        }
    //                    }
    //
    //                    @Override
    //                    public void onSuccess() {
    //                        LogUtil.e("加入群组成功,进入聊天");
    //                        ChatActivity.startGroupChat(SelectPindanLandActivity.this, groupId);
    //                        finish();
    //                    }
    //                });
    //    }

    public void updateGroupID() {
        final String groupId = TimeUtil.getNowTimeLong() + "";
        LogUtil.e("创建群组Id-->" + groupId);
        GroupMemberInfo memberInfo = new GroupMemberInfo();
        memberInfo.setAccount(TIMManager.getInstance().getLoginUser());
        mMembers.add(0, memberInfo);
        GroupChatInfo groupChatInfo = new GroupChatInfo();
        String groupName = "振航打药";
        groupChatInfo.setChatName(groupName);
        groupChatInfo.setGroupName(groupName);
        groupChatInfo.setMemberDetails(mMembers);
        groupChatInfo.setGroupType("Public");
        groupChatInfo.setJoinType(2);
        groupChatInfo.setNotice("notice TAO");
        GroupChatManager.getInstance().createGroupChat(groupChatInfo, groupId, new IUIKitCallBack() {
            @Override
            public void onSuccess(Object data) {
                MessageInfo msg = (MessageInfo) data;
                SessionInfo sessionInfo = new SessionInfo();
                sessionInfo.setGroup(true);
                sessionInfo.setTitle("滴滴打药");
                sessionInfo.setPeer(((MessageInfo) data).getPeer());
                sessionInfo.setLastMessage(msg);
                UIKitRequest request = new UIKitRequest();
                request.setModel(UIKitRequestDispatcher.MODEL_SESSION);
                request.setAction(UIKitRequestDispatcher.SESSION_ACTION_START_CHAT);
                request.setRequest(sessionInfo);
                UIKitRequestDispatcher.getInstance().dispatchRequest(request);
                updataGroupId(groupId);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                LogUtil.e("创建群组失败" + module + "   " + errCode + "   " + errMsg);
            }
        });
    }

    public void updataGroupId(final String groupId) {
        HTTPAPI.getInstance().updataGroupId(groupId, pinDanId, userId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("群组ID提交成功" + s);
                ChatActivity.startGroupChat(SelectPindanLandActivity.this, groupId);
                finish();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("群组ID提交失败" + e.getMessage());
            }
        });
    }
}
